package com.llmm.aspect;

import com.alibaba.fastjson.JSONObject;
import com.llmm.utils.IPUtil;
import com.llmm.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 日志操作切面
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Resource
    private LogMapper logMapper;

    @Autowired
    private HttpServletRequest request;

    //出现自定义注解时，自动匹配
    @Pointcut("@annotation(com.llmm.aspect.SysControllerLog)")
    public void pointcut() {

    }

    //pointcut()方法执行前执行
    @Before("pointcut()")
    public void syslogAction(JoinPoint point){
        // TODO: 2022/1/27 使用方法获取session中的 账号信息
        String userId ="admin";
        // 登录ip
        String ip = IPUtil.getRealIp(request);
        //请求类型：post,delete,put,get
        String requestType = request.getMethod();
        // 请求地址
        String serviceURI = request.getRequestURI();
        //获取方法名字
        String methodName = point.getSignature().getName();

        /*try {
            //获取参数
            //获取方法
            Method method = getMethod(point);
            SysControllerLog annotation = method.getAnnotation(SysControllerLog.class);
            String keyType =null;
            if (StringUtil.isNotEmpty(annotation.detail())){
                JSONObject paramJson = JSONObject.parseObject(annotation.detail());
                keyType = paramJson.getString("key");
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }*/

        SysLog sysLog = new SysLog();
        sysLog.setUserId(userId);
        sysLog.setIp(ip);
        sysLog.setAction(requestType+":"+methodName);
        sysLog.setUrl(serviceURI);
        sysLog.setActionAt(new Date());
        logMapper.insertActionLog(sysLog);

    }

    //获取方法
    private Method getMethod(JoinPoint point) throws NoSuchMethodException {
        Signature signature = point.getSignature();
        MethodSignature msig = (MethodSignature) signature;
        Object target = point.getTarget();
        return target.getClass().getMethod(msig.getName(),msig.getParameterTypes());
    }


}
